import { createRouter, createWebHistory } from 'vue-router'
// import Login from '../components/Login.vue'
import Login from '../components/Login.vue'
import Main from '../components/Main.vue'
import Index from '../components/mobile/index/Index.vue'
import Basket from '../components/mobile/basket/Basket.vue'
import My from '../components/mobile/my/My.vue'
import Message from '../components/mobile/message/Message.vue'
import AdminIndex from '../components/admin/Index.vue'
import AdminOverview from '../components/admin/Overview.vue'
import AdminUserManagement from '../components/admin/UserManagement.vue'
import AdminOrderManagement from '../components/admin/OrderManagement.vue'

const routes = [
  { path: '/', redirect: '/index' },
  {
    path: '/main',
    component: Main,
    children: [
      {
        path: '/index',
        component: Index

      },
      {
        path: '/basket',
        component: Basket
      },
      {
        path: '/my',
        component: My
      },
      {
        path: '/message',
        component: Message
      }
    ]
  },
  { path: '/login', component: Login },
  {
    path: '/admin',
    component: AdminIndex,
    redirect: '/overview',
    guards: true,
    children: [
      {
        path: '/overview',
        component: AdminOverview,
        guards: true
      },
      {
        path: '/usermanagement',
        component: AdminUserManagement,
        guards: true
      },
      {
        path: '/ordermanagement',
        component: AdminOrderManagement,
        guards: true
      }
    ]
  }
]

const router = createRouter({
  /*
    createWebHistory() 不带#
    createWebHashHistory() 带#
  */
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 导航守卫
  for (var i = 0; i < routes.length; i++) {
    if (to.path === routes[i].path && !routes[i].guards) {
      return next()
    }
    if (routes[i].children) {
      for (let ii = 0; ii < routes[i].children.length; ii++) {
        if (to.path === routes[i].children[ii].path && !routes[i].children[ii].guards) {
          return next()
        }
      }
    }
  }
  var username = window.sessionStorage.getItem('username')
  if (!username) {
    next('/login')
  }
  return next()
})

export default router
